#!/usr/bin/perl

# This script generates a (text) pgm (portable greymap) file based on
# a list of text pbm (portable bitmap) source files by adding each bit
# of the pbm files together.  This was originally used to create an
# alpha transition for Cyberlink PowerDirector by converting a series
# of images into PBMs.  The increasing dark portions of the source
# images would result in darker areas on the greyscale image.
#
# The resulting greymap can be converted into a PNG and imported as an
# alpha transition into PowerDirector.

$rows = 0;
$cols = 0;

while ($#ARGV >= 0)
{
    $fn = shift(@ARGV);
    open(INPUT,"<$fn") or die "Unable to open $fn: $!\n";
    # lazily assume each image is the same size
    $magic = <INPUT>;
    chomp $magic;
    $res = <INPUT>;
    chomp $res;
    ($cols,$rows) = split(/ /,$res);
    print STDERR "$fn is $rows x $cols\n";
    $row = $col = 0;
    while (<INPUT>)
    {
	chomp;
#	print join ",", unpack("b*",$_);
	printf(STDERR "len=%d\n",length($_));
	for $i (0..length($_)-1)
	{
	    # pbm 1=black, 0=white...
	    $image[$row][$col] += 1-int(substr($_,$i,1));
#	    print "$row,$col=$image[$row][$col] ";
	    printf(STDERR "%4d %4d\n",$col,$row);
	    $col++;
	    $col %= $cols;
	    if ($col == 0) { $row++; }
	}
    }
}

# PGM header
print "P2\n$cols $rows\n255\n";
for ($row=0; $row<$rows; $row++)
{
    for ($col=0; $col<$cols; $col++)
    {
	if ($col % 17 > 0) { print " "; }
	print $image[$row][$col];
	if ($col % 17 == 16) { print "\n"; }
    }
    print "\n";
}

1;
